/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.common.mapper;

import com.google.common.collect.Lists;
import org.dozer.DozerBeanMapper;
import org.dozer.classmap.RelationshipType;
import org.dozer.loader.api.BeanMappingBuilder;
import org.dozer.loader.api.FieldsMappingOptions;
import org.dozer.loader.api.TypeMappingOptions;
import org.springframework.context.annotation.Bean;

import java.util.Collection;
import java.util.List;

import static org.dozer.loader.api.FieldsMappingOptions.*;
import static org.dozer.loader.api.TypeMappingOptions.*;

/**
 * Encapsulate the Dozer to implement the deep translation Mapper which for Bean<->Bean:
 * <p>
 * 1. hold the single instance of Mapper.
 * 2. translate class type of the return value.
 * 3. translate the all objects in Collection.
 * 4. ake a distinction between creating a new one and copy to an existed one.
 * <p>
 * Created by Peter.Li on 2015/10/9.
 */
public class BeanMapper {

    /**
     * Hold the Dozer single instance to avoid consume memory of repeat creating.
     */
    private static DozerBeanMapper dozer = new DozerBeanMapper();

    public  static BeanMappingBuilder builder = new BeanMappingBuilder() {
        protected void configure() {
            mapping(Bean.class, Bean.class,
                    TypeMappingOptions.oneWay(),
                    mapId("A"),
                    mapNull(false)
            );
        }
    };

    /**
     * Base to Dozer translation object.
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        return dozer.map(source, destinationClass);
    }

    /**
     * Base to Dozer translate the object's class type which in Collection.
     */
    public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        List<T> destinationList = Lists.newArrayList();
        for (Object sourceObject : sourceList) {
            T destinationObject = dozer.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

    /**
     * Base to Dorzer copy values of A to B.
     */
    public static void copy(Object source, Object destinationObject) {
        dozer.map(source, destinationObject);
    }

}